iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 6
2

我們常有時候希望子元件某部分模板(template)可以讓開發人員在父元件自己客製化,這時候就會用到插槽(Slot),這個概念是不是很像生活當中的插頭與插座呢?沒錯,趕快來瞭解吧。

做法其實相當簡單,我們在欲客制化子元件之模板安插slot,再帶name命名;
在父元件使用 template 標籤加上指令v-slot,指定插入哪個插槽,例如:

父元件:

<child-component>
    <template v-slot:header>
        <h2>Hello World</h2>
    </template>
    <template v-slot:default>
        <p>And the default.</p>
    </template>
    <template #footer>
        <p>Here's footer</p>
      </template>
</child-component>

子元件:

...
<strong>
    <slot name="header"></slot>
    <slot></slot>
    <slot name="footer"></slot>
</strong>
...

若 slot 不帶name命名,父組件v-slot隱含名為 default,亦可省略default。父層如欲使用縮寫語法#,則需具名。

---我是分隔線-------------------------------

我們在父元件決定子元件樣板時,有些情況會需要子元件的變數,那要怎麼做呢?
這時候我們需要在子元件將資料綁定(v-bind);在父元件使用v-slot指令將其資料接出來。

父元件:

<template v-slot:price="slotProps">
    <h2>{{ 特價: price*slotProps.discount }}</h2>
    <h4>{{ 原價: $499 }}</h4>
</template>

子元件:

...
<span>
    <slot name="price" :discount="discount"></slot>
</span>
...

有任何問題歡迎下方留言,如果喜歡我的文章別忘了按讚、訂閱追蹤加分享唷!!
---我是分隔線-----------------------------------------------------------
PollyPO技術-前端設計轉前端工程師-JS踩坑雜記 30 天
喬依司-實作經典 JavaScript 30
五百億-Vue CLI + Firebase 雲端資料庫 30天打造簡易部落格及後臺管理
eien_zheng-前端小嘍嘍的Golang學習旅程_The journey of learning Golang


上一篇
Day05 自己的國家自己救-自己的v-model自己定義
下一篇
Day07 今晚我想來點不一樣的動態元件,"is" 屬性
系列文
忍住不打牌位,只要30天VueJS帶你上A牌30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言